package com.dudu.timer;

import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.List;
import java.util.Properties;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.app.VelocityEngine;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

import com.dudu.bean.ReportDailyBean;
import com.dudu.dao.DailyReportDao;
import com.dudu.service.IOperationPlatformService;
import com.dudu.service.impl.OperationPlatformServiceImpl;
import com.dudu.utils.DateUtils;
import com.dudu.utils.DictionaryUtils;

import core.CoreDao;
import core.CoreDaoInvoke;
import core.util.EmailSend;

/**
 * 嘟一下客户周报
 * 统计周期是周一0点至周五中午12点
 * 企业名称、账号、产品名称、使用量、单位
 * @author jack
 * @time 2017-06-08
 */
public class WeeklyReportJobBak implements Job {
	//log日志
	public static final Logger log = core.util.Logger.getLogger(WeeklyReportJobBak.class.getName());
	//数据库连接
	private CoreDao coreDao = CoreDaoInvoke.getInstance();
	//日报表dao
	private DailyReportDao dailyReportDao = new DailyReportDao();
	//运营平台地址
	private IOperationPlatformService operationPlatformServiceImpl = new OperationPlatformServiceImpl();
	//日报客户
	//private ReportCustDao reportCustDao = new ReportCustDao();

	@Override
	public void execute(JobExecutionContext arg0) throws JobExecutionException {
		log.info("执行嘟一下客户周报job");
		try{		
			String emailAdressStr = DictionaryUtils.getValueByTypeAndKey("report_email", "weekly");	//获得日报表接收邮箱
			if(StringUtils.isNotBlank(emailAdressStr)){			
				StringBuffer content = new StringBuffer();	//邮件内容
				String monday = "";
				String firday = "";
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
				Calendar cal = Calendar.getInstance();
				firday = sdf.format(cal.getTime()) + " 12:00:00";//格式"2017-06-09 12:00:00"
				cal.add(Calendar.DAY_OF_MONTH, -4);
				monday = DateUtils.getTimeAddBeginStr(sdf.format(cal.getTime())) ; 		//格式"207-06-05 00:00:00"
				JSONArray appArray =  operationPlatformServiceImpl.queryAppItems("", "", "99653B0C7EC6897C2F426C0E13A9D66C", 1, 200).optJSONArray("data");
				//客户周消费统计
				this.reportWeeklyByApp(content, monday, firday, appArray);
				String[] emailAdressArray = emailAdressStr.split(",");
				
				for(String emailAdress:emailAdressArray){
					Thread.sleep(1000*10); //邮件服务器不支持连续发送
					EmailSend.sendMail(emailAdress, "嘟一下客户周报" + monday + " - " + firday, content.toString(), null, null); //发送邮件
				}
				
			}else{
				log.error("未配置周报表接收邮件地址");
			}
		}catch(Exception ex){
			ex.getMessage();
			log.error("嘟一下周报表error");
		}
	}
	
	
	
	/**
	 * 客户周消费统计
	 * @param content
	 * @param beginTime
	 * @param endTime
	 * @param appArray
	 * @throws UnsupportedEncodingException 
	 */
	private void reportWeeklyByApp(StringBuffer content, String beginTime, String endTime, JSONArray appArray) throws UnsupportedEncodingException {
		if(StringUtils.isNotBlank(beginTime) && StringUtils.isNotBlank(endTime) && appArray!=null){	
			List<ReportDailyBean> reportDailyBeanList = new ArrayList<ReportDailyBean>();	
			for(int i=0; i<appArray.size(); i++){
				JSONObject appJson = appArray.getJSONObject(i);
				//String isvName = appJson.optString("isv_name");
				//String appName = appJson.optString("app_name");
				String appKey = appJson.optString("app_key");
				//1、获取所有计费账号
				List<JSONObject> dataList = this.dailyReportDao.queryActiveCustaccountByAppAndTime(coreDao, appKey, beginTime, endTime);
				//List<JSONObject> dataList = this.reportCustDao.queryAll(coreDao);
				if(dataList != null){
					for(int j=0;j<dataList.size();j++){
						//2、统计计费账号各产品的使用量
						JSONObject data = dataList.get(j);
						String custAccount = data.optString("cust_account");
						String custName =  URLDecoder.decode(operationPlatformServiceImpl.queryCustomerInfo(custAccount).optString("cust_name"), "UTF-8");
						
						List<JSONObject> list = this.dailyReportDao.queryTotalTimeByCustaccountAndTime(coreDao, custAccount, beginTime, endTime);
						for(int k=0;k<list.size();k++){
							JSONObject obj = list.get(k);
							//String custAccount = obj.optString("cust_account");
							String productCode = obj.optString("ability_type");
							String totalTime = obj.optString("total_time");
							String unit = obj.optString("unit");
							
							ReportDailyBean reportDailyBean = new ReportDailyBean();
							reportDailyBean.setCustName(custName);  
							reportDailyBean.setCustAccount(custAccount);
							reportDailyBean.setProductName(this.converProductCodeToName(productCode));
							reportDailyBean.setTotalTime(totalTime);
							reportDailyBean.setUnit(unit);
							reportDailyBeanList.add(reportDailyBean);
						}
						
						
					}
				}
			}
			
			Collections.sort(reportDailyBeanList);
			 
			try {			
				String reportDailyContent = getTempleteContent("vm/reportWeeklyCust.vm", reportDailyBeanList);
				content.append(reportDailyContent); 					
			} catch (Exception e) {
				e.printStackTrace();
				log.error("客户周统计报表渲染模板error");
			}
		}
	}

	/**
	 * 产品编码和名称的转换
	 * @param productCode
	 * @return
	 */
	private String converProductCodeToName(String productCode){
		String productName = "";
		if("MPTY".equals(productCode)){
			productName = "多方通话";
		}else if("DIAL".equals(productCode)){
			productName = "两方通话";
		}else if("VOICE".equals(productCode)){
			productName = "语音通知";
		}else if("VOICEBATCH".equals(productCode)){
			productName = "语音通知(批量)";
		}else if("VCAPTCHA".equals(productCode)){
			productName = "语音验证码";
		}else if("SMMS".equals(productCode)){
			productName = "短信";
		}else if("ADSMMS".equals(productCode)){
			productName = "营销短信";
		}else if("CALLRECORDER".equals(productCode)){
			productName = "录音";
		}else if("IVVR".equals(productCode)){
			productName = "语音调研";
		}else if("VOICE70".equals(productCode)){
			productName = "70字语音套餐产品";
		}else if("VOICE140".equals(productCode)){
			productName = "140字语音套餐产品";
		}
		return productName;
	}

	/**
	 * 解析模板
	 * @param templete
	 * @param list
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings({ "deprecation", "rawtypes" })
	public static String getTempleteContent(String templete, List list) throws Exception {
		StringWriter writer = null;
		try {
			URL url = Thread.currentThread().getContextClassLoader().getResource("");
			String realPath = url.getPath();
			VelocityEngine ve = new VelocityEngine();
			Properties p = new Properties();
			p.put(Velocity.FILE_RESOURCE_LOADER_PATH, URLDecoder.decode(realPath));
			ve.init(p);
			Template t = ve.getTemplate(templete, "UTF-8");
			VelocityContext context = new VelocityContext();
			context.put("array", list);
			writer = new StringWriter();
			t.merge(context, writer);
		} catch (Exception e) {
			log.info("<===获得模板出错==>");
			e.printStackTrace();
			throw e;
		}
		return writer.toString();
	}

	public static void main(String[] args) {

	}

}
